package com.example.foodiemoments

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.foodiemoments.databinding.ActivityMainBinding
import com.example.foodiemoments.ui.fragments.AiChefFragment
import com.example.foodiemoments.ui.fragments.HomeFragment
import com.example.foodiemoments.ui.fragments.MapFragment
import com.example.foodiemoments.ui.fragments.ProfileFragment
import com.example.foodiemoments.ui.fragments.PublishFragment

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    // Fragment 实例
    private val homeFragment by lazy { HomeFragment() }
    private val aiChefFragment by lazy { AiChefFragment() }
    private val publishFragment by lazy { PublishFragment() }
    private val mapFragment by lazy { MapFragment() }
    private val profileFragment by lazy { ProfileFragment() }

    private var currentFragment: Fragment? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setupBottomNavigation()

        // 默认显示首页
        if (savedInstanceState == null) {
            switchFragment(homeFragment)
        }
    }

    private fun setupBottomNavigation() {
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_home -> {
                    switchFragment(homeFragment)
                    true
                }
                R.id.nav_ai_chef -> {
                    switchFragment(aiChefFragment)
                    true
                }
                R.id.nav_publish -> {
                    switchFragment(publishFragment)
                    true
                }
                R.id.nav_map -> {
                    switchFragment(mapFragment)
                    true
                }
                R.id.nav_profile -> {
                    switchFragment(profileFragment)
                    true
                }
                else -> false
            }
        }
    }

    private fun switchFragment(fragment: Fragment) {
        if (fragment == currentFragment) return

        val transaction = supportFragmentManager.beginTransaction()

        // 隐藏当前Fragment
        currentFragment?.let {
            transaction.hide(it)
        }

        // 显示目标Fragment
        if (fragment.isAdded) {
            transaction.show(fragment)
        } else {
            transaction.add(R.id.fragmentContainer, fragment)
        }

        transaction.commit()
        currentFragment = fragment
    }
}
